#!/bin/env/python3
import logging

from info import redis_store, db
from . import index_blue

from flask import current_app, render_template, session, jsonify, request, g

from ...models import User, News, Category
from ...utils.commons import user_login_data
from ...utils.response_code import RET


@index_blue.route('/newslist')
def newlist():
    # 获取参数
    cid = request.args.get("cid", "1")
    page = request.args.get('page', '1')
    page_size = request.args.get('per_page', "10")
    # 参数类型转换
    try:
        page = int(page)
        page_size = int(page_size)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        page_size = 10
    # 分页查询
    try:
        # Flase ：查询不到不报错
        # 判断 cid是否为1
        #
        # if cid == "1":
        #     paginate = News.query.order_by(News.create_time.desc()).paginate(page,
        #                                                                      page_size,
        #                                                                      False)
        #
        # else:
        #     paginate = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(page,
        #                                                                                                      page_size, False)
        # 代码改进:
        filters = [News.status == 0]
        if cid != "1":
            filters.append(News.category_id == cid)
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, page_size, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")

    # 获取到分页对象中的属性，总页数，当前页，当前页的对象列表
    current_Page = paginate.page
    print()
    total_Page = paginate.pages
    items = paginate.items

    # 将对象列表转成字典列表
    news_list = []
    for new in items:
        news_list.append(new.to_dict())

    # 拼接数据，返回
    return jsonify(errno=RET.OK, errmsg="", totalPage=total_Page, currentPage=current_Page, newsList=news_list)


@index_blue.route('/', methods=['GET', 'POST'])
@user_login_data
def index():
    # 获取用户信息
    # user_id = session.get("user_id")
    #
    # # 通过user_id 取出用户对象
    # user = None
    # if user_id:
    #     try:
    #         user = db.session.query(User).get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 查询热门新闻
    try:
        news = db.session.query(News).order_by(News.clicks.desc()).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")
        # 查询新闻分类
    try:
        news_cate = Category.query.all()
        print(news_cate)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取分类失败")
        # 将分类渲染
    cate_list = []
    for cate in news_cate:
        cate_list.append(cate.to_dict())
    print(cate_list)
    # 将新闻的对象列表转成字典列表
    # 拼接用户数据，渲染页面
    news_list = []
    for item in news:
        news_list.append(item.to_dict())
    data = {
        "user_info": g.user.to_dict() if g.user else "",
        "news": news_list,
        "news_cate": cate_list
    }
    print(news_list)

    # 测试redis 存取
    # redis_store.set("name", "zhangtiantian")
    # print(redis_store.get("name"))

    # # 测试session 存取
    # session["name"] = "zhangsan"
    # print(session.get("name"))
    # 没有继承日志之前，使用print输出不方便做控制
    # 使用日志记录方法logging进行输出可控
    # logging.debug("输入调试信息")
    # logging.info("info---")
    # logging.error("error---")
    # logging.warning("warning---")
    # 也可以使用 current_app
    # current_app.logger.debug("debug--")
    return render_template("news_/index.html", data=data)


# 处理网站logo
@index_blue.route('/favicon.ico')
def get_web_log():
    return current_app.send_static_file("news/favicon.ico")


# 统一返回404.html
@index_blue.route('/404')
@user_login_data
def page_not_found():
    data = {
        "user_info": g.user.to_dict() if g.user else ""
    }
    return render_template("news_/404.html", data=data)
